package com.kay.springbootRESTful.service;

import com.kay.springbootRESTful.entity.Account;
import com.kay.springbootRESTful.entity.Customer;
import com.kay.springbootRESTful.repository.AccountRepository;
import com.kay.springbootRESTful.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * @Author Kay
 * @Date: 2019/12/12 15:55
 */

@Service
public class AccountService {

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private CustomerRepository customerRepository;

    public Account save(Integer customerId, Account account) {
        return customerRepository.findById(customerId).map(customer -> {
            account.setCustomer(customer);
            return accountRepository.save(account);
        }).orElseThrow(() -> new RuntimeException("Customer [customerId =" + customerId + "] can't be found"));
    }

    public ResponseEntity<Account> update(Integer customerId, Account newAccount) {
        Customer customer = customerRepository.findById(customerId).orElseThrow(
                () -> new RuntimeException("Customer [customerId =" + customerId + "] can't be found")
        );
        return accountRepository.findById(newAccount.getAccountNumber()).map(account -> {
            newAccount.setCustomer(customer);
            accountRepository.save(newAccount);
            return ResponseEntity.ok(newAccount);
        }).orElseThrow(() -> new RuntimeException("Account [accountNumber =" + newAccount.getAccountNumber() + "] can't be found"));
    }

    public Page<Account> findAll(Integer customerId, Pageable pageable) {
        return accountRepository.findByCustomer_CustomerId(customerId, pageable);
    }

    public ResponseEntity<?> delete(Integer customerId, Integer accountNumber) {
        if (!customerRepository.existsById(customerId)) {
            throw new RuntimeException("Customer [customerId=" + customerId + "] can't be found");
        }

        return accountRepository.findById(accountNumber).map(account -> {
            accountRepository.delete(account);
            return ResponseEntity.ok().build();
        }).orElseThrow(() -> new RuntimeException("Account [accountNumber =" + accountNumber + "] can't be found"));
    }
}
